
from pathlib import Path
import yaml
import re
import sys
def yaml_load(file='data.yaml', append_filename=False):
    """
    Load YAML data from a file.

    Args:
        file (str, optional): File name. Default is 'data.yaml'.
        append_filename (bool): Add the YAML filename to the YAML dictionary. Default is False.

    Returns:
        (dict): YAML data and file name.
    """
    assert Path(file).suffix in ('.yaml', '.yml'), f'Attempting to load non-YAML file {file} with yaml_load()'
    with open(file, errors='ignore', encoding='utf-8') as f:
        s = f.read()  # string

        # Remove special characters
        if not s.isprintable():
            s = re.sub(r'[^\x09\x0A\x0D\x20-\x7E\x85\xA0-\uD7FF\uE000-\uFFFD\U00010000-\U0010ffff]+', '', s)

        # Add YAML filename to dict and return
        data = yaml.safe_load(s) or {}  # always return a dict (yaml.safe_load() may return None for empty files)
        if append_filename:
            data['yaml_file'] = str(file)
        return data
    


SimpleNamespace = type(sys.implementation)
class IterableSimpleNamespace(SimpleNamespace):
    """
    Ultralytics IterableSimpleNamespace 是 SimpleNamespace 的扩展类，添加了可迭代功能，并支持与 dict() 和 for 循环一起使用。
    """

    def __iter__(self):
        """返回命名空间属性的键-值对迭代器。"""
        return iter(vars(self).items())

    def __str__(self):
        """返回对象的人类可读的字符串表示形式。"""
        return '\n'.join(f'{k}={v}' for k, v in vars(self).items())

    def __getattr__(self, attr):
        """自定义属性访问错误消息，提供有用的信息。"""
        name = self.__class__.__name__

    def get(self, key, default=None):
        """如果存在指定的键，则返回其值；否则返回默认值。"""
        return getattr(self, key, default)
